package operator;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.VoidFunction;
import scala.Tuple2;

import java.util.Arrays;
import java.util.List;

/**
 * Created by huangxiaoli on 2019/11/27 13:49
 */
public class reduceByKey {

    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setAppName("reduceByKey")
                .setMaster("local");

        JavaSparkContext sc = new JavaSparkContext(conf);
        List<Tuple2<String, Integer>> scoreList = Arrays.asList(
                new Tuple2<String, Integer>("class1", 80),
                new Tuple2<String, Integer>("class2", 90),
                new Tuple2<String, Integer>("class1", 97),
                new Tuple2<String, Integer>("class2", 89));

        JavaPairRDD<String, Integer> scores = sc.parallelizePairs(scoreList);

        //reduceByKey算法返回的RDD，还是JavaPairRDD<key,value>
        JavaPairRDD<String, Integer> totalScores = scores.reduceByKey(new Function2<Integer, Integer, Integer>() {
            @Override
            public Integer call(Integer v1, Integer v2) throws Exception {
                return v1 + v2;
            }
        });

        totalScores.foreach(new VoidFunction<Tuple2<String,Integer>>() {
            @Override
            public void call(Tuple2<String, Integer> t) throws Exception {
                System.out.println(t._1 + ":" + t._2);

            }
        });
        sc.close();
    }

}
